<template>
  <div class="personal-center">
    <UserProfileBG />
    <!-- 用户信息卡片 -->
    <div class="user-info-card">
      <h2 class="info-title">个人信息</h2>
      <div class="user-info-content">
        <div class="info-item">
          <label>用户ID:</label>
          <span>{{ userInfo.user_id }}</span>
        </div>
        <div class="info-item">
          <label>用户名:</label>
          <span>{{ userInfo.username }}</span>
        </div>
        <div class="info-item">
          <label>Email:</label>
          <span>{{ userInfo.email }}</span>
        </div>
        <div class="info-item">
          <label>注册时间:</label>
          <span>{{ userInfo.created_at }}</span>
        </div>
        <el-button
          class="edit-btn"
          color="rgb(121.3, 187.1, 255)"
          @click="isEditDialogVisible = true"
          >编辑信息</el-button
        >
      </div>
    </div>

    <!-- 编辑信息表单对话框 -->
    <el-dialog
      title="编辑个人信息"
      v-model="isEditDialogVisible"
      width="400px"
      @close="resetForm"
    >
      <el-form :model="editForm" ref="editForm" label-width="100px">
        <el-form-item label="昵称">
          <el-input
            v-model="editForm.username"
            placeholder="请输入昵称"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            v-model="editForm.password"
            placeholder="请输入密码"
            type="password"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input
            v-model="editForm.email"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="isEditDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="updateUserInfo">确定更改</el-button>
      </template>
    </el-dialog>

    <!-- 选项卡 -->
    <el-tabs v-model="activeTab" type="border-card" class="custom-tabs">
      <el-tab-pane name="posts">
        <template #label>
          <span class="tabs-label-posts">
            <el-icon><Postcard /></el-icon>
            <span>我的帖子</span>
          </span>
        </template>
        <transition name="fade">
          <div class="post-list">
            <div v-for="post in posts" :key="post.post_id" class="post-item">
              <h3>{{ post.title }}</h3>
              <p>{{ post.content }}</p>
              <div class="post-actions">
                <span>{{ post.created_at }}</span>
                <el-button
                  color="#626aef"
                  :dark="isDark"
                  plain
                  size="small"
                  @click="deletePost(post.post_id)"
                  >删除</el-button
                >
              </div>
            </div>
          </div>
        </transition>
      </el-tab-pane>

      <el-tab-pane name="photos" :key="activeTab">
        <template #label>
          <span class="tabs-label-photos">
            <el-icon><Picture /></el-icon>
            <span>我的图片</span>
          </span>
        </template>
        <transition name="fade">
          <!-- 瀑布流图片展示 -->
          <div class="photo-list">
            <div
              v-for="(photo, index) in photos"
              :key="photo.photo_id || index"
              class="photo-item"
            >
              <el-card class="photo-card" :body-style="{ padding: '0' }">
                <el-image
                  :src="photo.url"
                  lazy
                  fit="cover"
                  class="photo-image"
                  :preview-src-list="[photo.url]"
                />
                <div class="photo-info">
                  <span class="photo-title">{{ photo.title }}</span>
                  <span class="photo-category">{{ photo.category }}</span>
                </div>
                <div class="photo-actions">
                  <el-button
                    size="mini"
                    type="text"
                    class="delete-button"
                    @click="deletePhoto(photo.photo_id)"
                  >
                    删除
                  </el-button>
                </div>
              </el-card>
            </div>
          </div>
        </transition>
      </el-tab-pane>

      <el-tab-pane label="我的活动" name="events">
        <template #label>
          <span class="tabs-label-events">
            <el-icon><Calendar /></el-icon>
            <span>我的活动</span>
          </span>
        </template>
        <transition name="fade">
          <div class="event-list">
            <div
              v-for="event in events"
              :key="event.event_id"
              class="event-item"
            >
              <h3>{{ event.title }}</h3>
              <p>{{ event.description }}</p>
              <div class="meta-info">
                <div class="events-info-item">
                  <el-icon><Location /></el-icon>
                  <span>{{ event.location }}</span>
                </div>
                <div class="events-info-item">
                  <el-icon><Clock /></el-icon>
                  <span>{{ formatDate(event.event_date) }}</span>
                </div>
                <div class="event-actions">
                  <el-button
                    color="rgb(255, 201, 231)"
                    :dark="isDark"
                    plain
                    round
                    size="small"
                    @click="deleteEvent(event.event_id)"
                    >删除</el-button
                  >
                </div>
              </div>
            </div>
          </div>
        </transition>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { useRouter } from 'vue-router';
import UserProfileBG from '../../components/UserProfileBG.vue'

const router = useRouter();

export default {
  components: {
    UserProfileBG // 注册组件
  },
  data() {
    return {
      activeTab: "posts", // 默认选中帖子
      userInfo: {},
      posts: [],
      photos: [],
      events: [],
      isEditDialogVisible: false, // 控制编辑对话框显示
      editForm: {
        username: "", // 用于表单填写的昵称
        password: "", // 用于表单填写的密码
        email: "", // 用于表单填写的邮箱
      },
    };
  },

  mounted() {
    this.fetchUserInfo();
    this.fetchUserPosts();
    this.fetchUserPhotos();
    this.fetchUserEvents();
  },

  methods: {
    formatDate(dateString) {
      return new Date(dateString).toLocaleString();
    },
    async fetchUserInfo() {
      try {
        if (this.$store.state.user_id === null) {
          // 如果状态没有加载，跳转到登录页面
          router.push("/user/login"); // 跳转到登录页面
          this.$message.error("登录状态失效，请重新登录！");
          return; // 防止继续执行后续代码
        }
        const response = await this.$axios.get(
          `/user/${this.$store.state.user_id}`
        );
        this.userInfo = response.data;
      } catch (error) {
        console.error("获取用户信息失败:", error);
      }
    },
    async fetchUserPosts() {
      try {
        if (this.$store.state.user_id === null) {
          // 如果状态没有加载，跳转到登录页面
          router.push("/user/login"); // 跳转到登录页面
          this.$message.error("登录状态失效，请重新登录！");
          return; // 防止继续执行后续代码
        }
        const response = await this.$axios.get(
          `/posts/user/${this.$store.state.user_id}`
        );
        this.posts = response.data;
      } catch (error) {
        console.error("获取用户帖子失败:", error);
      }
    },
    async fetchUserPhotos() {
      try {
        if (this.$store.state.user_id === null) {
          // 如果状态没有加载，跳转到登录页面
          router.push("/user/login"); // 跳转到登录页面
          this.$message.error("登录状态失效，请重新登录！");
          return; // 防止继续执行后续代码
        }
        const response = await this.$axios.get(
          `/photos/user/${this.$store.state.user_id}`
        );
        this.photos = response.data;
      } catch (error) {
        console.error("获取用户图片失败:", error);
      }
    },
    async fetchUserEvents() {
      try {
        if (this.$store.state.user_id === null) {
          // 如果状态没有加载，跳转到登录页面
          router.push("/user/login"); // 跳转到登录页面
          this.$message.error("登录状态失效，请重新登录！");
          return; // 防止继续执行后续代码
        }
        const response = await this.$axios.get(
          `/events/user/${this.$store.state.user_id}`
        );
        this.events = response.data;
      } catch (error) {
        console.error("获取用户活动失败:", error);
      }
    },
    async deletePost(postId) {
      await this.$axios.delete(`/posts/${postId}`);
      this.fetchUserPosts();
    },
    async deletePhoto(photoId) {
      await this.$axios.delete(`/photos/${photoId}`);
      this.fetchUserPhotos();
    },
    async deleteEvent(eventId) {
      await this.$axios.delete(`/events/${eventId}`);
      this.fetchUserEvents();
    },
    // 打开编辑对话框时触发
    showEditDialog() {
      this.isEditDialogVisible = true;
    },
    // 提交修改的用户信息
    async updateUserInfo() {
      if (this.$store.state.user_id === null) {
        // 如果状态没有加载，跳转到登录页面
        router.push("/user/login"); // 跳转到登录页面
        this.$message.error("登录状态失效，请重新登录！");
        return; // 防止继续执行后续代码
      }
      const userId = this.$store.state.user_id;
      const formData = new FormData();
      formData.append("username", this.editForm.username);
      formData.append("password", this.editForm.password);
      formData.append("email", this.editForm.email);

      try {
        // 发送请求更新用户信息
        await this.$axios.put(`/user/${userId}`, formData);
        // 手动更新 userInfo，立即反映前端数据
        this.userInfo = { ...this.userInfo, ...this.editForm };
        // 显示成功提示
        this.$message.success("个人信息更新成功");
        // 使用 $nextTick 确保对话框关闭的操作发生在 DOM 更新之后
        this.$nextTick(() => {
          this.isEditDialogVisible = false; // 关闭对话框
        });
      } catch (error) {
        this.$message.error("更新个人信息失败");
        console.error("更新个人信息失败:", error);
      }
    },
    // 重置表单
    resetForm() {
      this.editForm = {
        username: this.userInfo.username,
        password: "", // 清空密码
        email: this.userInfo.email,
      };
    },
  },
};
</script>

<style scoped>
* {
  box-sizing: border-box;
}

/* 个人中心容器 */
.personal-center {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #ffffff;
  box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.2);
}

/* 用户信息卡片 */
.user-info-card {
  background: linear-gradient(135deg, #f9c5d1, #fbc2eb);
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  color: #fff;
  box-shadow: 3px 3px 10px rgba(0, 0, 0, 0.2);
}

.info-title {
  text-align: center;
}

.user-info-content {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  padding: 24px;
  max-width: 500px;
  margin: 20px auto;
  display: flex;
  flex-direction: column; /* 垂直排列内容 */
  align-items: flex-start; /* 默认情况下内容左对齐 */
  padding-left: 16px; /* 添加左侧内边距 */
  padding-right: 16px; /* 添加右侧内边距 */
  box-sizing: border-box; /* 让 padding 和 border 包含在宽度计算中 */
}

.info-item {
  display: flex;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: background 0.2s ease;
  width: 100%;
  box-sizing: border-box; /* 确保 padding 和 border 被包含在宽度内 */
}

.info-item:hover {
  background: #f1f3f5;
}

.info-item label {
  min-width: 100px;
  color: #666;
  font-weight: 500;
  margin-right: 16px;
  font-size: 14px;
}

.info-item span {
  color: #333;
  font-weight: 600;
  font-size: 14px;
  flex-grow: 1;
  word-break: break-word;
}

.edit-btn {
  width: 300px; /* 设置按钮的宽度 */
  height: 40px; /* 设置按钮的高度 */
  border-radius: 10px; /* 设置按钮的圆角 */
  opacity: 0.6; /* 设置按钮的透明度 */
  justify-content: center; /* 设置按钮的居中 */
  align-self: center; /* 使按钮在容器中水平居中 */
  margin-top: 20px; /* 增加与上方内容的间距 */
}
.edit-btn:hover {
  opacity: 1;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(121, 187, 255, 0.3);
}

/* 选项卡样式 */
.custom-tabs {
  background: #c2e38c;
  border-radius: 20px;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.2);
}

.tabs-label-posts,
.tabs-label-photos,
.tabs-label-events {
  /* 设置垂直居中 */
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 过渡动画 */
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}
.fade-enter,
.fade-leave-to {
  opacity: 20;
}

/* 帖子、图片、活动列表 */
.post-list,
.photo-list,
.event-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  padding: 10px;
}

/* 帖子卡片 */
.post-item,
.photo-item,
.event-item {
  flex: 1 1 300px; /* flex-grow, flex-shrink 和 flex-basis */
  max-width: 100%; /* 确保宽度不超过父容器 */
  background-color: #fff3f3;
  border-radius: 10px;
  padding: 15px;
  transition: transform 0.3s;
  box-sizing: border-box; /* 确保 padding 和 border 不影响宽度 */
}

.post-item:hover,
.photo-item:hover,
.event-item:hover {
  transform: scale(1.02);
}

/* 图片 */
/* 瀑布流布局容器 */
.photo-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); /* 适配宽度 */
  gap: 16px; /* 图片间距 */
  padding: 10px;
}

/* 每个图片项 */
.photo-item {
  width: 98%;
  box-sizing: border-box; /* 确保 padding 和边框不影响宽度 */
}

/* 图片卡片 */
.photo-card {
  position: relative;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  overflow: hidden;
  width: 100%; /* 确保图片卡片宽度适应容器 */
}

/* 图片 */
.photo-image {
  width: 100%;
  height: 300px;
  object-fit: cover; /* 保证图片按比例适配 */
  border-radius: 8px 8px 0 0;
}

/* 图片信息栏 */
.photo-info {
  padding: 10px;
  background: #a5dbff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-top: 1px solid #f0f0f0;
}

/* 图片功能栏 */
.photo-actions {
  position: absolute;
  bottom: 0px;
  right: 80px;
  display: flex;
  align-items: center;
  gap: 10px;
  background: rgba(236, 48, 117, 0.6);
  padding: 4px 6px;
  border-radius: 8px;
}

/* 活动相关 */
.events-info-item {
  display: flex;
  align-items: center;
  gap: 5px;
  background: rgb(255, 251, 231);
}

/* 媒体查询：响应式设计 */
@media (max-width: 768px) {
  .personal-center {
    padding: 10px;
  }

  .user-info-card {
    padding: 15px;
  }

  .user-info-content {
    max-width: 100%;
    padding-left: 8px;
    padding-right: 8px;
  }

  .edit-btn {
    width: 80%;
  }

  .photo-item {
    width: auto; /* 确保图片项占满屏幕 */
    max-width: 83%;
    padding: 0; /* 避免内边距造成溢出 */
  }

  .photo-image {
    width: 100%;
    height: auto; /* 确保图片高度按比例自动调整 */
  }
}
</style>
